package cn.marinda.entity;
import cn.marinda.config.PropertiesServerConfig;
import cn.marinda.factory.ServerConfigFactory;
import cn.marinda.gui.impl.TipsDialogImpl;
import lombok.Data;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务器信息
 *
 *
 * @author admin
 * @date 2022/07/08
 */
@Data
public class ServerInfo {

//    核心数
    private String cpuCount;
//    使用率
    private String cpuRate;
//    CPU名称
    private String cpuName;

//    最大内存数
    private String ramTotal;
//    内存使用率
    private String ramRate;
//    使用多少GB
    private String ramCount;
//    剩余多少内存
    private String ramSurplus;

    private File file;

    public ServerInfo(){

    }


    /**
     * 得到eula文件
     *
     * @return {@link File}
     */
    public File getEulaFile(){
        file = new File(Server.SERVER_RESET_SERVER.getPath(),"eula.txt");
        if(!file.exists()){
            return null;
        }
        return file;
    }

    /**
     * 创建eula文件
     *
     * @return boolean
     */
    public boolean createEulaFile() throws IOException {
            file = new File(Server.SERVER_RESET_SERVER.getPath(), "eula.txt");
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
            bufferedWriter.write("eula=true");
            bufferedWriter.flush();
            bufferedWriter.close();
            if(file.createNewFile()) return true;
            return false;
    }

    /**
     * 创建服务器属性文件
     *
     * @return boolean
     */
    public boolean createServerPropertiesFile() throws IOException {
        file = new File(Server.SERVER_RESET_SERVER.getPath(), "server.properties");
        if (!file.exists()) {
            loadPropertiesInfo();
            return true;
        }
        if(file.createNewFile())loadPropertiesInfo();
        return true;
    }

    /**
     * 加载属性信息
     */
    private void loadPropertiesInfo() throws IOException {
        List<String> value = bindPropertiesDefaultConfig();
        writeListToConfig(value);
    }

    private List<String> bindPropertiesDefaultConfig() {
        List<String> propertiesList = new ArrayList<>();
        propertiesList.add("view-distance=10");
        propertiesList.add("max-build-height=256");
        propertiesList.add("server-ip=");
        propertiesList.add("level-seed=");
        propertiesList.add("allow-nether=true");
        propertiesList.add("gamemode=0");
        propertiesList.add("enable-command-block=false");
        propertiesList.add("server-port=25565");
        propertiesList.add("enable-rcon=false");
        propertiesList.add("enable-query=false");
        propertiesList.add("op-permission-level=4");
        propertiesList.add("prevent-proxy-connections=false");
        propertiesList.add("generator-settings=");
        propertiesList.add("resource-pack=");
        propertiesList.add("player-idle-timeout=0");
        propertiesList.add("level-name=world");
        propertiesList.add("motd=A Minecraft Server");
        propertiesList.add("force-gamemode=false");
        propertiesList.add("debug=false");
        propertiesList.add("hardcore=false");
        propertiesList.add("white-list=false");
        propertiesList.add("broadcast-console-to-ops=true");
        propertiesList.add("pvp=true");
        propertiesList.add("spawn-npcs=true");
        propertiesList.add("spawn-animals=true");
        propertiesList.add("generate-structures=true");
        propertiesList.add("snooper-enabled=true");
        propertiesList.add("difficulty=1");
        propertiesList.add("network-compression-threshold=256");
        propertiesList.add("level-type=DEFAULT");
        propertiesList.add("spawn-monsters=true");
        propertiesList.add("max-players=20");
        propertiesList.add("spawn-protection=16");
        propertiesList.add("resource-pack-sha1=");
        propertiesList.add("online-mode=false");
        propertiesList.add("allow-flight=false");
        propertiesList.add("max-world-size=29999984");
        return propertiesList;
    }

    /**
     * 将List数据写入到Config中
     */
    public void writeListToConfig(List<String> configList) throws IOException {
            FileOutputStream outputStream = new FileOutputStream(file);
            for (String config : configList) {
                outputStream.write(config.getBytes(StandardCharsets.UTF_8));
                outputStream.write("\r\n".getBytes(StandardCharsets.UTF_8));
            }
            outputStream.flush();
            outputStream.close();
    }

    /**
     * 获取服务器属性
     *
     * @return {@link File}
     */
    public File getServerProperties(){
        file = new File(Server.SERVER_RESET_SERVER.getPath(),"server.properties");
        if(!file.exists()){
            return null;
        }
        return file;
    }




    /**
     * 读取服务器文件配置
     *
     * @param file 文件
     * @return {@link Map}<{@link String}, {@link Object}>
     */
    public Map<String,Object> readServerFileConfig(File file) {
        Map<String, Object> objectMap = new HashMap<>();
        try {
            BufferedReader inputStream = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
//            byte[] bytes = new byte[inputStream..];
//            int len = 0;
            String str = "";
            while((str = inputStream.readLine()) != null){
                int splitValue = str.indexOf("=");
                String key = str.substring(0, splitValue);
                String value = str.substring(splitValue + 1);
                objectMap.put(key,value);
            }
//            while((len = inputStream.read(bytes)) != -1){
//                inputStream.read
//                String str = new String(inputStream.read(bytes,0,len),"utf-8");
//                if (str.indexOf("=") <=0) {
//                    continue;
//                }
//                inputStream.read()
//
//            }
            inputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return objectMap;
    }

    /**
     * 通过map反写服务器文件配置
     *
     * @param file 文件
     * @return void
     */
    public void writeServerFileConfig(File file,Map<String,Object> fileConfigMap) {
        BufferedWriter bufferedWriter = null;
        try {
            StringBuilder sb = new StringBuilder();
            FileOutputStream outputStream = new FileOutputStream(file);
            fileConfigMap.keySet().stream().forEach(element -> {
                String key = element;
                String value = fileConfigMap.get(key).toString();
                sb.append(key+"=".concat(value) + "\n");
            });
            outputStream.write(sb.toString().getBytes(StandardCharsets.UTF_8));
            bufferedWriter.flush();
            bufferedWriter.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
